package engine.audio;

/**
 * AudioBuffer
 * Implementation of a standard AudioBuffer_I
 **/
public class AudioBuffer implements AudioBuffer_I {
	/**
	 * CtoR
	 * @param bufferSize - The size, in bytes, to initialize to.
	 * @throws IllegalArgumentException - If bufferSize <= 0
	 **/
	public AudioBuffer(int bufferSize) {
		if(bufferSize <= 0) {
			throw new IllegalArgumentException("bufferSize must be greater than zero.");
		}
		_Buffer = new byte[bufferSize];
		_Size = bufferSize;
		_Tail = 0;
	}
	
	protected int _Size;
	protected int _Tail;
	protected final byte[] _Buffer;
	
	// AudioBuffer_I -----------------------------------------------------------
	@Override
	public int getSize() {
		return _Size;
	}
	@Override
	public int getFree() {
		return _Size - _Tail;
	}
	@Override
	public void clear() {
		_Tail = 0;
	}
	@Override
	public int fill(byte[] inBuffer, int length) {
		// Sanity checking.
		if(inBuffer == null || length <= 0) {
			return 0;
		}
		if(length > (_Size - _Tail)) {
			length = _Size - _Tail;
		}
		if(length > inBuffer.length) {
			length = inBuffer.length;
		}
		System.arraycopy(inBuffer, 0, _Buffer, _Tail, length);
		_Tail += length;
		return length;
	}
	@Override
	public int drain(byte[] outBuffer, int length) {
		// Sanity checking.
		if(outBuffer == null || length <= 0) {
			return 0;
		}
		if(length > _Tail) {
			length = _Tail;
		}
		if(length > outBuffer.length) {
			length = outBuffer.length;
		}
		
		System.arraycopy(_Buffer, 0, outBuffer, 0, length);
		// Realign remaining data to the beginning of the buffer.
		int remainder = _Tail - length;
		if(remainder > 0) {
			System.arraycopy(_Buffer, length, _Buffer, 0, remainder);
		}
		_Tail = length;
		return length;
	}
	@Override
	public byte[] getData() {
		return _Buffer;
	}
}